package com.security;

import javax.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author t-zhaoheng
 * @since 2022/3/28
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  @Resource
  MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;

  @Resource
  MyAuthenticationFailureHandler myAuthenticationFailureHandler;

  @Resource
  MyAuthenticationEntryPoint myAuthenticationEntryPoint;

  @Resource
  MyAccessDeniedHandler myAccessDeniedHandler;

  @Resource
  MyUserDetailsService userDetailsService;

  @Resource
  DynamicPermission dynamicPermission;

  @Bean
  JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter() {
    JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter = new JwtAuthenticationTokenFilter();
    return jwtAuthenticationTokenFilter;
  }

  @Bean
  MyUsernamePasswordAuthenticationFilter myUsernamePasswordAuthenticationFilter() throws Exception {
    MyUsernamePasswordAuthenticationFilter filter = new MyUsernamePasswordAuthenticationFilter();
    //成功后处理
    filter.setAuthenticationSuccessHandler(myAuthenticationSuccessHandler);
    //失败后处理
    filter.setAuthenticationFailureHandler(myAuthenticationFailureHandler);

    filter.setAuthenticationManager(authenticationManagerBean());
    return filter;
  }

  @Bean
  public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
  }

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    // 用户认证方式，可以有三种方式
    // 1. 使用SpringSecurity默认的账号和密码,{username: "user", password: "控制台随机生成"}
    // 2. 在这里或者配置文件写死
    // auth.inMemoryAuthentication().withUser("admin").password("123456").roles().and().withUser("zhangsan").password("123").roles();
    // 3. 连接数据库，校验用户名和密码，这样必须实现 UserDetailsService 接口
    auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and().headers().cacheControl();
    // 当用户输入 /login 时，拦截请求
    http.addFilterAt(myUsernamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    // 使用SpringEL表达式，在dynamicPermission类中动态校验用户的权限
    http.authorizeRequests().antMatchers(HttpMethod.POST,"/**/register").permitAll()
        .anyRequest().access("@dynamicPermission.checkPermission(request,authentication)")
      ;
    http.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    http.exceptionHandling().authenticationEntryPoint(myAuthenticationEntryPoint).accessDeniedHandler(myAccessDeniedHandler);

  }

  @Override
  public void configure(WebSecurity web) throws Exception {
    // 配置静态资源放行
    web.ignoring().antMatchers("/front/**", "/upload/**", "/admin/**", "/error");
    web.ignoring().antMatchers("/biaoqianfenlei/list","/biaoqianfenlei/detail/**","/option/**/**","/follow/**/**","/remind/**/**/**","/cal/**/**","/group/**/**","/value/**/**/**","/value/**/**/**/**","/matchFace","/config/list","/config/detail/**","/discusszhishixinxi/list","/discusszhishixinxi/detail/**","file/download","/news/list","/news/detail/**","/storeup/detail/**","/user/login","/user/register","/user/resetPass","/xiangmufenlei/list","/xiangmufenlei/detail/**","/yonghu/login","/yonghu/register","/yonghu/resetPass","/yonghu/page","/yonghu/list","/yonghu/detail/**","/zhishixinxi/list","/zhishixinxi/detail/**","/zhishixinxi/autoSort", "/matchPassword");
  }
}
